package ide.ccf.ccdesigner.cpp.wizards.pages;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;

import ide.ccf.ccdesigner.cpp.wizards.DesignerFormsWizard;

/**
 * “新建”向导页面允许为新文件和新文件名设置容器。该页面将只接受无扩展名或者扩展名符合指定的规则（ui）的文件名。
 *
 */
public class DesignerFormsWizardPage extends WizardPage 
{
	private Text containerText;
	private Text fileText;
	private List templateList;
	private Label preview;

	private ISelection selection;

	/**
	 * 构造器
	 * @param selection
	 */
	public DesignerFormsWizardPage(ISelection selection) 
	{
		super("wizardPage");
		setTitle("窗体设计文件模板");
		this.selection = selection;
	}

	/**
	 * 创建向导对话框控制
	 * 
	 * @see IDialogPage#createControl(Composite)
	 */
	public void createControl(Composite parent) 
	{
		Composite container = new Composite(parent, SWT.NULL);
		GridLayout layout = new GridLayout();
		container.setLayout(layout);
		
		layout.numColumns = 3;
		layout.verticalSpacing = 9;
		
		Label label = new Label(container, SWT.NULL);
		label.setText("源文件夹(&S):");

		containerText = new Text(container, SWT.BORDER | SWT.SINGLE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		containerText.setLayoutData(gd);
		containerText.addModifyListener(new ModifyListener() 
		{
			public void modifyText(ModifyEvent e) 
			{
				dialogChanged();
			}
		});
		
		Button button = new Button(container, SWT.PUSH);
		button.setText("浏览(&B)...");
		button.addSelectionListener(new SelectionAdapter() 
		{
			public void widgetSelected(SelectionEvent e) 
			{
				handleBrowse();
			}
		});
				
		Composite templateComposite = new Composite(container, SWT.NULL);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		gridLayout.horizontalSpacing = 10;
		gridLayout.marginWidth = 0;
		templateComposite.setLayout(gridLayout);
		
		gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 3;
		templateComposite.setLayoutData(gd);
		
		label = new Label(templateComposite, SWT.NULL);
		label.setText("模板:");
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		label.setLayoutData(gd);
		
		templateList = new List(templateComposite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
		templateList.addSelectionListener(new SelectionListener() 
		{
		      public void widgetSelected(SelectionEvent event) 
		      {
		        updateTemplate();
		      }
		      
		      public void widgetDefaultSelected(SelectionEvent event) 
		      {
		          updateTemplate();
		      }
		});
		templateList.setSize(80, 150);
		
		gd = new GridData();
		gd.verticalAlignment = SWT.FILL;
		gd.grabExcessVerticalSpace = true;
		templateList.setLayoutData(gd);
				
		preview = new Label(templateComposite, SWT.NONE);
		preview.setSize(150, 150);
		gd = new GridData();
		gd.verticalAlignment = SWT.FILL;
		gd.grabExcessVerticalSpace = true;
		preview.setLayoutData(gd);
		
		label = new Label(container, SWT.NULL);
		label.setText("源文件名(&F):");

		fileText = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		fileText.setLayoutData(gd);
		fileText.addModifyListener(new ModifyListener() 
		{
			public void modifyText(ModifyEvent e) 
			{
				dialogChanged();
			}
		});
		
		insertTemplates();
		initialize();
		dialogChanged();
		setControl(container);
		updateTemplate();
	}
	
	/**
	 * 插入模板
	 */
	private void insertTemplates()
	{
		InputStream stream = getClass().getResourceAsStream(DesignerFormsWizard.TEMPLATE_LOCATION + "/templates.txt");
		
        if (stream != null) 
        {
            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
            try 
            {
                String s = null;
                while ((s = r.readLine()) != null) 
                {
                	templateList.add(s.replace('_', ' '));
                	
                    if (s.equals("Widget")) 
                    {
                    	templateList.setSelection(templateList.getItemCount() - 1);                        
                    }
                }
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        } 
        else 
        {
            System.out.println("无法找到窗体设计文件模板。");
        }
	}
	
	/**
	 * 更新模板
	 */
	private void updateTemplate()
	{
		Image image = null;
        try 
        {
        	String name = DesignerFormsWizard.TEMPLATE_LOCATION + "/" + templateList.getSelection()[0] + ".png";
            name = name.replace(' ', '_');
            InputStream stream = getClass().getResourceAsStream(name);
            image = new Image(preview.getDisplay(), stream);
        } 
        catch (RuntimeException e) 
        {
        }

        preview.setImage(image);
        preview.pack();        
	}

	/**
	 * 初始化，测试当前工作台选择是否是一个适合使用的容器
	 */
	private void initialize() 
	{
		if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) 
		{
			IStructuredSelection ssel = (IStructuredSelection) selection;
			
			if (ssel.size() > 1)
				return;
			
			Object obj = ssel.getFirstElement();
			
			if (!(obj instanceof IResource) && (obj instanceof IAdaptable))
				obj = ((IAdaptable)obj).getAdapter(IResource.class);
			
			if (obj instanceof IResource) 
			{
				IContainer container;
				
				if (obj instanceof IContainer)
					container = (IContainer) obj;
				else
					container = ((IResource) obj).getParent();
				
				containerText.setText(container.getFullPath().makeRelative().toString());
			}
		}	
		fileText.setFocus();
	}

	/**
	 * 使用标准容器选择对话框
	 */
	private void handleBrowse() 
	{
		ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(), false, "选择源文件夹");
		
		if (dialog.open() == ContainerSelectionDialog.OK) 
		{
			Object[] result = dialog.getResult();
			if (result.length == 1) 
			{
				containerText.setText(((Path) result[0]).makeRelative().toString());
			}
		}
	}

	/**
	 * 对话框改变处理。确保两个文本框的值都不为空。
	 */
	private void dialogChanged() 
	{
		IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getContainerName()));
		String fileName = getFileName();

		if (getContainerName().length() == 0) 
		{
			updateStatus("源文件夹为空。");
			return;
		}
		if (container == null || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) 
		{
			updateStatus("源文件夹不存在。");
			return;
		}
		if (!container.isAccessible()) 
		{
			updateStatus("项目不可写。");
			return;
		}
		if (fileName.length() == 0) 
		{
			updateStatus("源文件名为空。");
			return;
		}
		if (fileName.replace('\\', '/').indexOf('/', 1) > 0) 
		{
			updateStatus("源文件名不合法。");
			return;
		}
		
		final IFile file = ((IContainer)container).getFile(new Path(fileName));
		updateStatus(file.toString());
		if (file.exists()) 
		{
			updateStatus("源文件已经存在。");
			return;
		}
		
		String ext = "";
		int dotLoc = fileName.lastIndexOf('.');
		if (dotLoc != -1) 
		{
			ext = fileName.substring(dotLoc + 1);
		}
		
		if (ext.equalsIgnoreCase("ui") == false) 
		{
			updateStatus("源文件扩展名必需为\"ui\"。");
			return;
		}
		updateStatus(null);
	}

	/**
	 * 更新状态
	 * @param message
	 */
	private void updateStatus(String message) 
	{
		setErrorMessage(message);
		setPageComplete(message == null);
	}

	/**
	 * 获取容器名称
	 * @return
	 */
	public String getContainerName() 
	{
		return containerText.getText();
	}

	/**
	 * 获取源文件名
	 * @return
	 */
	public String getFileName() 
	{
		return fileText.getText();
	}
	
	/**
	 * 获取模板名称
	 * @return
	 */
	public String getTemplateName()
	{
		String name = DesignerFormsWizard.TEMPLATE_LOCATION + "/" + templateList.getSelection()[0] + ".ui";
		return name.replace(' ', '_');
	}
}